package graphics;

import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.ScrollPaneConstants;
import javax.swing.JPanel;
import javax.swing.ButtonGroup;

import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;

import java.util.Observer;
import java.util.Observable;

public class GBuildingChooser extends JScrollPane {

    /** Attributs */
    private ButtonGroup m_buttonGroup;
    private GridBagConstraints m_gridBagConstraints;
    private JPanel m_panel;

    /** Constructeurs */
    public GBuildingChooser(ButtonGroup buttonGroup) {
        setWheelScrollingEnabled(true);
        setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        setBorder(null);
 
        m_buttonGroup = buttonGroup;
        m_panel = new JPanel(new GridBagLayout());
        m_gridBagConstraints = new GridBagConstraints();
        m_gridBagConstraints.gridx = 0;
        m_gridBagConstraints.gridy = GridBagConstraints.RELATIVE;
        m_gridBagConstraints.insets = new Insets(5,10,5,10);
            
        setViewportView(m_panel);
    }

    public void add(GBuildingFactory gBuildingFactory) {
        Item item = new Item(gBuildingFactory);
        m_panel.add(item, m_gridBagConstraints);
        m_buttonGroup.add(item);
    }

    /** Classes interne */
    public static class Item extends JToggleButton implements Observer, GStatusArea.Viewer {
    
        /** Variables de classe */
        final public static int largeur = 200, hauteur = 32;

        /** Attributs */
        private GBuildingFactory m_gBuildingFactory;

        /** Constructeurs */
        public Item(GBuildingFactory gBuildingFactory) {
            super(gBuildingFactory.getName());
            setPreferredSize(new Dimension(largeur, hauteur));
            setEnabled(gBuildingFactory.isEnabled());
            m_gBuildingFactory = gBuildingFactory;
            m_gBuildingFactory.addObserver(this);
        }

        /** Methodes */
        public void update(GStatusArea gStatusArea) {
            gStatusArea.setInfo(m_gBuildingFactory.getName(),
                                new GActivity(m_gBuildingFactory.getDefaultActivity(), null));
            gStatusArea.getGCity().setGBuildingFactory(m_gBuildingFactory);
        }
        
        public void update(Observable gBuildingFactory, Object gBuildingFactoryUpdate) {
            if (!m_gBuildingFactory.isEnabled()) {
                if (isSelected()) m_gBuildingFactory.getGCity().setGBuildingFactory(null);
                setEnabled(false);
            } else setEnabled(true);
        }
    }

}
